set more off

local J `1'

forvalues k = 1/`J' {
capture drop z_`k' x_`k'
gen z_`k' = z`k'*ismax
gen x_`k' = x`k'*ismax
*Set to 0 for own good
replace z_`k' = z_`k'*(z_`k'!=z)
replace x_`k' = x_`k'*(x_`k'!=x)
}

forvalues k = 1/`J' {
gen zorig_`k' = z_`k'
gen xorig_`k' = x_`k'


replace z_`k' = bz_`k'*z_`k'
replace x_`k' = bx_`k'*x_`k'
}

forvalues k = 1/`J' {
gen zz_`k' = b2z_`k'*z*zorig_`k'
gen zx_`k' = b2x_`k'*z*xorig_`k'

}

gen zzmax = z*ismax
if(`J'==2) replace zzmax = 0

capture drop zzsum zxsum zsum xsum zxzsum zxxsum
gen zzsum = 0
gen zxsum = 0
gen zsum = 0
gen xsum = 0

forvalues k = 1/`J' {
replace zzsum = zzsum + zz_`k'
replace zxsum = zxsum + zx_`k'
replace zsum = zsum+ z_`k'
replace xsum = xsum+ x_`k'
}

